module Seiso::ImportMaster::Validators
  # Author:: Willie Wheeler (mailto:wwheeler@expedia.com)
  # Copyright:: Copyright (c) 2014-2016 Expedia, Inc.
  # License:: Apache 2.0
  class NodeValidator < BaseValidator

    def initialize
      @log = Seiso::ImportMaster::Util::Logger.new "NodeValidator"
    end

    def validate(doc)
#      @log.info "Validating nodes"
      validate_si_key doc
      validate_nodes doc
    end

    private

    def validate_si_key(doc)
      si_key = doc['serviceInstance']

      if si_key.nil?
        error 'Node document must contain a serviceInstance field containing the service instance key.'
      end
    end

    def validate_nodes(doc)
      nodes = doc['items']

      if nodes.nil?
        error "Node document must contain an items field containing the service instance's nodes."
      end

      nodes.each do |n|
        node_name = n['name']

        if node_name.nil?
          error "Every node must have a name."
        end

        # Fail if the node has a serviceInstance field. This is legacy, and we don't want it anymore, because
        # people will think that they can move a node from one service instance to another by changing this field.
        if n['serviceInstance']
          error "Node #{node_name} must not contain a serviceInstance field. " \
             "Specify the service instance using the document-level serviceInstance field."
        end

        if n['machine'].nil?
          error "Node #{node_name} must have a machine."
        end
      end

    end
  end
end
